package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.es.SkuHasStockTo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockLockedDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderFeignService orderFeignService;


    /**
     * 最终解锁，私有方法
     * @param skuId
     * @param wareId
     * @param num
     * @param taskDetailId
     */
    private void unlockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        //库存解锁
        this.wareSkuDao.unlockStock(skuId, wareId, num);
        //更新库存工作单的状态
        WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity();
        taskDetailEntity.setId(taskDetailId);
        taskDetailEntity.setLockStatus(2); //变为已解锁
        this.wareOrderTaskDetailService.updateById(taskDetailEntity);
    }

    /**
     * 分页查询
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        /**
         * skuId: 9
         * wareId: 1
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (StringUtils.isNotEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotEmpty(skuId)) {
            queryWrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 增加库存
     * @param skuId
     * @param wareId
     * @param skuNum
     */
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1.判断如果还没有这个库存记录
        List<WareSkuEntity> wareSkuEntities = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (CollectionUtils.isEmpty(wareSkuEntities)) { //新增
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字,如果失败,不需要回滚
            //TODO 异常出现不回滚?高级部分再讲解
            try {
                R r = productFeignService.info(skuId);
                if (r.getCode() == 0) {
                    Map<String, Object> skuInfo = (Map<String, Object>) r.get("skuInfo");
                    wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                }
            } catch (Exception e) {

            }

            wareSkuEntity.setSkuName("");
            this.wareSkuDao.insert(wareSkuEntity);
        } else { //更新
            this.wareSkuDao.addStock(skuId, wareId, skuNum);
        }
    }

    /**
     * 查询skus是否有库存
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockTo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockTo> tos = skuIds.stream().map(skuId -> {
            SkuHasStockTo to = new SkuHasStockTo();

            //查询当前sku的总库存量
            //SELECT SUM(stock - stock_locked) FROM `wms_ware_sku` WHERE sku_id = 15
            Long count = this.baseMapper.getSkuStock(skuId);
            to.setSkuId(skuId);
            to.setHasStock(count == null ? false : count > 0);
            return to;
        }).collect(Collectors.toList());
        return tos;
    }

    /**
     * 为某个订单锁定库存
     * 默认只要是运行时异常,都会回滚
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        /**
         * 保存库存工作单详情,便于追溯
         */
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);

        //1.按照下单的收货地址,找到一个就近的仓库,锁定库存(暂不使用)
        //1.找到每个商品在哪个仓库都有库存，将所有要锁的sku，封装到一个list
        List<OrderItemVo> locks = vo.getLocks();

        List<SkuWareHasStock> skuWareHasStocks = locks.stream().map(orderItemVo -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();

            Long skuId = orderItemVo.getSkuId();
            skuWareHasStock.setSkuId(skuId);
            skuWareHasStock.setLockNum(orderItemVo.getCount());
            //查询这个商品在哪里有库存
            List<Long> wareIds = this.wareSkuDao.listWareIdHasSkuStock(skuId);
            skuWareHasStock.setWareIds(wareIds);

            return skuWareHasStock;
        }).collect(Collectors.toList());

        //2.锁定库存，每个sku，挨个锁库存
        for (SkuWareHasStock skuWareHasStock : skuWareHasStocks) {
            Boolean skuStocked = false;
            Long skuId = skuWareHasStock.getSkuId();
            List<Long> wareIds = skuWareHasStock.getWareIds();
            if (CollectionUtils.isEmpty(wareIds)) {
                //没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }

            for (Long wareId : wareIds) { //挨个仓库锁,能锁到就行
                //受影响的行数=1就成功了,=0就失败了
                Long count = this.wareSkuDao.lockSkuStock(skuId, wareId, skuWareHasStock.getLockNum());
                if (count == 1) {
                    //锁库存成功
                    skuStocked = true;
                    //告诉MQ库存锁定成功，1代表锁定成功
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(
                            null,
                            skuId,
                            null,
                            skuWareHasStock.getLockNum(),
                            wareOrderTaskEntity.getId(),
                            wareId,
                            1);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);

                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setTaskId(wareOrderTaskEntity.getId());
                    StockLockedDetailTo stockLockedDetailTo = new StockLockedDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, stockLockedDetailTo);
                    stockLockedTo.setDetail(stockLockedDetailTo);

                    //每个sku的锁库存详情，发送消息
                    //如果发生异常，也没关系，库存工作单回滚，释放库存的消息就查不到id
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);

                    break;
                } else {
                    //当前仓库锁失败,锁下一个仓库

                }
            }
            if (skuStocked == false) {
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }

        //3.肯定全部都是锁定成功的

        return true;
    }

    /**
     * 定时扫描，解锁库存
     * @param to
     */
    @Override
    public void unlockStock(StockLockedTo to) {

        StockLockedDetailTo detail = to.getDetail();
        Long skuId = detail.getSkuId();
        Integer skuNum = detail.getSkuNum();
        Long wareId = detail.getWareId();

        Long detailId = detail.getId();
        //解锁
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(detailId);
        if (detailEntity != null) {
            //库存已经成功锁定了
            Long taskId = to.getTaskId(); //库存工作单的id
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(taskId);
            String orderSn = taskEntity.getOrderSn();

            R r = this.orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                //订单数据返回成功
                OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {
                });
                if (orderVo == null || orderVo.getStatus() == 4) {
                    //订单不存在,或者订单已经被取消,仅这种时候需要解锁
                    if (detailEntity.getLockStatus() == 1) {
                        //当前库存工作单详情,状态1:已锁定
                        this.unlockStock(skuId, wareId, skuNum, detailId);
                    }
                }
            } else {
                //拒绝消息，重新解锁
                throw new RuntimeException("远程服务失败");
            }

        } else {
            //自己锁库存失败,已经回滚了,无需解锁,直接消费
        }
    }

    /**
     * 订单关闭,手动解锁
     *
     * @param orderTo
     */
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查一下最新的库存解锁状态,防止重复解锁库存
        WareOrderTaskEntity taskEntity = this.wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long taskId = taskEntity.getId();
        //按照工作单找到所有没有解锁的库存,进行解锁
        List<WareOrderTaskDetailEntity> taskDetailEntities = wareOrderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>()
                        .eq("task_id", taskId)
                        .eq("lock_status", 1));

        for (WareOrderTaskDetailEntity entity : taskDetailEntities) {
            this.unlockStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }

    }

    /**
     * 当前sku在哪些仓库有库存
     */
    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer lockNum;
        private List<Long> wareIds;
    }

}